Ext.ns('App', 'App.document');

/**
 * @class App.document.FormPanel
 * A typical FormPanel extension
 */
App.document.Form = Ext.extend(Ext.form.FormPanel, {
	
    name: 'document-form',
    id: 'document-form',
	//renderTo: 'user-form',
    //iconCls: 'silk-user',
    layout:'form',
    //frame: true,
    border: false,
    labelAlign: 'top',
    title: 'Detalles del Documento',
    width: 500,
    defaultType: 'textfield',
    defaults: {
        anchor: '100%'
    },
    autoScroll: true,
    autowidth: false,
    buttonAlign: 'center',
    labelSeparator: '',
    
    // privates properties
    
    //grid linked with the form
    linkedGrid: null,

    // private A pointer to the currently loaded record
    record: null,
    application: null,
    gridStoreRecord: null,
    
    // Json store used to populate documentType combo
    documentTypeJSONStore: new Ext.data.JsonStore({
		proxy: new Ext.data.HttpProxy({
			url: BASE_URL + 'documents/getDocumentTypes',
			method: 'POST'
		}),
		fields: ['id','documentType'],
		root: 'rows',
		autoLoad: true
	}),
	
	// proxy used to communicate data to the form
	proxy: new Ext.data.HttpProxy({
		api: {
			read: BASE_URL + 'documents/getDocumentDetailed',
			create: BASE_URL + 'documents/create', 
			update: BASE_URL + 'documents/update'
		},
		method: 'POST'
	}),
	
	documentReader: null,
	documentWriter: new Ext.data.JsonWriter({
	    encode: true,
	    writeAllFields: false
	}),
	
	// Store to cache documents on the client side
	documentDetailsStore: null,

	// used to hold the store writer state
	writerWriteAllFieldsState: null,
	// used to load the record 
	refreshRecord: false,
	
	FIELDMESSAGE_BLANKTEXT: 'Este campo es requerido.',
	FIELDMESSAGE_INVALIDTEXT: 'El valor entrado es inv&aacute;lido.',
	
    /**
     * initComponent
     * @protected
     */
    initComponent : function() {
        // build the form-fields.  Always a good idea to defer form-building to a method so that this class can
        // be over-ridden to provide different form-fields
        this.items = this.buildForm();

        // build form-buttons
        this.buttons = this.buildUI();

        // add a create event for convenience in our application-code.
        this.addEvents({
            /**
             * @event create
             * Fires when user clicks [create] button
             * @param {FormPanel} this
             * @param {Object} values, the Form's values object
             */
            create : true
        });
        
        /*
        this.on({
        	actioncomplete: function(form, action) {
                if(action.type == 'load'){
                    submit.enable();
                }
            }
        });
*/

        // super
        App.document.Form.superclass.initComponent.call(this);
    },

    
    /**
     * 
     * @private
     */
    buildFormByDocumentType: function(documentType) {
    	this.removeAll();
    	
    	this.add({
        	fieldLabel: 'Tipo', 
        	name: 'documentType',
          	xtype: 'combo',
          	allowBlank: false,
          	typeAhead: false,
          	//mode: 'local', 
          	triggerAction: 'query',
          	store: this.documentTypeJSONStore,
          	valueField: 'id',
          	displayField: 'documentType',
          	hiddenName: 'documentType',
          	width: 130, 
          	labelSeparator: '',
          	//forceSelection: true,
            //selectOnFocus: true,
          	//transform: 'documentType',
            lazyRender: true,
            loadingText: 'Cargando...',
            emptyText:'Seleccione un tipo de documento...',
          	listeners: {
          		/*
    			select: function(combo,r,i){ 
    				if( i != 0 ) {
    					//combo.buildFormByDocumentType();
    					console.log('DocumentForm line 130: reconstruct the form');
    					console.log(r, i);
    				}
          		},
          		*/
          		change: this.onDocumentTypeComboboxChange
          	}
          });
    	
        // common fields for all forms
        this.add({fieldLabel: 'Titulo', name: 'title', allowBlank: false, labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
        this.add({fieldLabel: 'Publicado en', name: 'publishedin', allowBlank: true, labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		this.add({fieldLabel: 'Autores', name: 'authors', xtype: 'textarea', allowBlank: false, labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		this.add({fieldLabel: 'A&ntilde;o', name: 'year', allowBlank: true, labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		this.add({fieldLabel: 'P&aacute;ginas', name: 'pages', xtype: 'textfield', labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		this.add({fieldLabel: 'Resumen', name: 'abstract', xtype: 'textarea', labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		this.add({fieldLabel: 'Tags', name: 'tags', allowBlank: true, xtype: 'textfield', labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		this.add({fieldLabel: 'Palabras claves suministradas por el autor', name: 'keywords', xtype: 'textfield', labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
        
    	switch( documentType ) {
	    	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS: 
	    		this.add({fieldLabel: 'Tutores', name: 'tutors', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Departamento', name: 'department', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Facultad', name: 'faculty', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: '&Aacute;rea del conocimiento', name: 'knowledgearea', xtype: 'textarea', maxlength: 255, listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		break;
	    	
	    	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS: 
	    		this.add({fieldLabel: 'Tutores', name: 'tutors', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Departamento', name: 'department', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Facultad', name: 'faculty', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: '&Aacute;rea del conocimiento', name: 'knowledgearea', xtype: 'textarea', maxlength: 255, listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		break;
	    	
	    	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS:
	    		this.add({fieldLabel: 'Tutores', name: 'tutors', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Departamento', name: 'department', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Facultad', name: 'faculty', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: '&Aacute;rea del conocimiento', name: 'knowledgearea', xtype: 'textarea', maxlength: 255, listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		break;
	    	
	    	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE:
				this.add({fieldLabel: 'Ciudad', name: 'city', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
				break;
			
	    	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK:
	    		this.add({fieldLabel: 'Ciudad', name: 'city', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Edici&oacute;n', name: 'edition', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Editores', name: 'editors', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Publicador', name: 'publisher', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		break;
	    		
	    	case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA:
	    		this.add({fieldLabel: 'Edici&oacute;n', name: 'edition', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'Publicador', name: 'publisher', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		this.add({fieldLabel: 'N&uacute;mero de Serie', name: 'series_number', xtype: 'textfield', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
	    		break;
    	}
    	
    	this.add({fieldLabel: 'URL', name: 'urls', allowBlank: true, xtype: 'textfield', labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
    	this.add({fieldLabel: 'Catalogos', name: 'catalogs', allowBlank: true, xtype: 'textfield', labelSeparator: '', listeners:{change: this.onChange}, blankText: this.FIELDMESSAGE_BLANKTEXT, invalidText: this.FIELDMESSAGE_INVALIDTEXT});
		
    	var filename = '';
    	if (typeof this.record.data.files == "object" && this.record.data.files instanceof Array) {
    		filename = this.record.data.files[0];
    	}
    	else {
    		filename = this.record.data.files;
    	}
    	
		var openPDFButton = new Ext.Button({
			text: 'Abrir archivo',
			style: {
                marginBottom: '20px'
            },
            iconCls: 'page_white_acrobat',
            handler: function(btn, ev) {
				var url = 'archivo/open/' + filename;
				window.open(url, '_newtab');
    			//location.replace(url);
    		},
    		scope: this
		});
		
		this.add({fieldLabel: 'Archivo', name: 'files', readOnly: true, xtype: 'textfield'/*, value: filename*/});
		this.add(openPDFButton);
		
		// build form-buttons
        //this.buttons = null;
        //this.addButtons();
		
    	this.doLayout();
    },
    
    buildRecordModelByDocumentType: function(documentType) {
    	var fields = new Array();
    	
    	// add default fields
    	fields = fields.concat([
			{name: 'title',  mapping: 'title'}, 
			{name: 'authors',  mapping: 'authors'}, 
			{name: 'documentType',  mapping: 'documentType'},
			{name: 'year',  mapping: 'year'}, 
			{name: 'pages',  mapping: 'pages'},
			{name: 'publishedin',  mapping: 'publishedin'},
			{name: 'abstract',  mapping: 'abstract'},
			{name: 'keywords',  mapping: 'keywords'},
			{name: 'tags', mapping: 'tags'},
			{name: 'urls', mapping: 'urls', convert: this.convertURLs},
			{name: 'files', mapping: 'files', convert: this.convertFiles},
			{name: 'catalogs', mapping: 'catalogs', convert: this.convertCatalogs}
			]);	
    	
    	switch( documentType ) {
    		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_THESIS:
    			fields = fields.concat([
    			    {name: 'tutors', mapping: 'tutors'},
    			    {name: 'department', mapping: 'department'},
    			    {name: 'faculty', mapping: 'faculty'},
    			    {name: 'knowledgearea', mapping: 'knowledgeArea'}
    			    ]);
    			break;
			
    		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MASTER_THESIS:
    			fields = fields.concat([
    			    {name: 'tutors', mapping: 'tutors'},
    			    {name: 'department', mapping: 'department'},
    			    {name: 'faculty', mapping: 'faculty'},
    			    {name: 'knowledgearea', mapping: 'knowledgeArea'}
    			    ]);
    			break;
    			
    		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_PHD_THESIS:
    			fields = fields.concat([
				    {name: 'tutors', mapping: 'tutors'},
				    {name: 'department', mapping: 'department'},
				    {name: 'faculty', mapping: 'faculty'},
				    {name: 'knowledgearea', mapping: 'knowledgeArea'}
				    ]);
    			break;
    			
    		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_MAGAZINE_ARTICLE:
    			fields = fields.concat([
				    {name: 'city', mapping: 'city'}
				    ]);
    			break;
    			
    		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_BOOK:
    			fields = fields.concat([
				    {name: 'city', mapping: 'city'},
				    {name: 'edition', mapping: 'edition'},
				    {name: 'editors', mapping: 'editors'},
				    {name: 'publisher', mapping: 'publisher'},
				    {name: 'knowledgearea', mapping: 'knowledgeArea'}
				    ]);
    			break;
    			
    		case myApp.DOCUMENT_TYPES_INTVALUE.DOCUMENT_TYPE_ENCYCLOPEDIA:
    			fields = fields.concat([
				    {name: 'edition', mapping: 'edition'},
				    {name: 'publisher', mapping: 'publisher'},
				    {name: 'series_number', mapping: 'series_number'}
				    ]);
    			break;
    	}
    	
    	return fields;
    },
    
    /**
     * buildform
     * @private
     */
    buildForm : function() {
    	return [];
    },
    /**
     * buildUI
     * @private
     */
    buildUI: function(){
    	//var filename = this.files[0].name;
        return [{
            text: 'Salvar',
            iconCls: 'icon-save',
            handler: this.onUpdate,
            scope: this
            //disabled: true
        }, {
            text: 'Crear copia',
            iconCls: 'silk-page-white-copy',
            width: 100,
            handler: this.onCreate,
            disabled: true,
            scope: this
        }, {
            text: 'Reset',
            iconCls: 'silk-page-white',
            handler: this.onReset,
            scope: this
        }];
        
    },
    
    addButtons: function() {
    	this.buttons = null;
    	this.addButton({
            text: 'Salvar',
            iconCls: 'icon-save'
            //handler: this.onUpdate,
            //scope: this
            //disabled: true
        }, this.onUpdate, this);
//    	this.addButton({
//            text: 'Reset',
//            iconCls: 'silk-page-white',
//            handler: this.onReset,
//            scope: this
//        });
    },
    
    /**
     * loadRecord
     * @param {Record} rec
     */
    loadRecord : function(rec) {
        var documentType = parseInt(rec.data.documentType);
        var recordModel = this.buildRecordModelByDocumentType(documentType);
        
        // as we build the form dynamically we must create the JsonReader here
        this.documentReader = null;
        this.documentReader = new Ext.data.JsonReader({
    	    totalProperty: 'documents',
    	    successProperty: 'success',
    	    idProperty: 'id',
    	    root: 'data',
    	    messageProperty: 'message',  // <-- New "messageProperty" meta-data
    	    fields: recordModel
    	});
        
        // typical Store collecting the Proxy, Reader and Writer together.
        this.documentDetailsStore = null;
    	this.documentDetailsStore = new Ext.data.Store({
    	    id: 'document',
    	    proxy: this.proxy,
    	    reader: this.documentReader,
    	    writer: this.documentWriter,
    	    autoSave: this.linkedGrid.store.autoSave, // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
    	    listeners: { write: this.onStoreWrite, load: this.onStoreLoad }
    	});
    	
    	// save the writer writeAllFields state
    	this.documentDetailsStore.writerWriteAllFieldsState = this.documentDetailsStore.writer.writeAllFields; 
    	this.documentDetailsStore.ownerCt = this;
        
    	// check if the rec.id == number 
    	// if it does then the data comes from the server
    	// otherwise the data has just been created in the client id == "ext-record-1"
    	
    	if( parseInt(rec.id) ) { // data comes from the server (autosave == true)
    		//console.log('Load from server');
    		
            /*
    		this.buildFormByDocumentType(documentType);
            this.getForm().load({
            	url:BASE_URL + 'documents/getDocumentDetailed', 
            	method:'POST', 
            	waitTitle: 'Por favor espere...', 
            	waitMsg:'Cargando detalles del documento.',
            	params: 'parameters={"id":'+rec.id+', "documentType": '+documentType+'}',
            	scope: this,
            	success: function(form, action) {
            		//var _this = action.options.scope;
            		myApp.setAlert(App.STATUS_NOTICE, action.result.message);
            		//console.log(action);
            		//Ext.Msg.alert('Success', action.result.message);
            	},
            	    
        	    failure: function(form, action) {
        	        switch (action.failureType) {
        	            case Ext.form.Action.CLIENT_INVALID:
        	                Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
        	                break;
        	            case Ext.form.Action.CONNECT_FAILURE:
        	                Ext.Msg.alert('Failure', 'Ajax communication failed');
        	                break;
        	            case Ext.form.Action.SERVER_INVALID:
        	               Ext.Msg.alert('Failure', action.result.msg);
        	       }
        	    }
            });
            */
            // set the base parameter to the store
            this.documentDetailsStore.setBaseParam('parameters', '{"id":'+rec.id+', "documentType": '+documentType+'}');
            var mask = new Ext.LoadMask(Ext.getBody()/*Ext.get('document-form')*/, {
            	msg: 'Cargando detalles del documento...', 
            	removeMask: true, 
            	store: this.documentDetailsStore
            });
            
            var result = this.documentDetailsStore.load({
            	callback: function(r, options, success) {
            		var _this = options.scope;
            		if( success ) {
            			_this.record = _this.documentDetailsStore.getById(rec.id);
            			_this.buildFormByDocumentType(documentType);
            	        _this.getForm().loadRecord(_this.record);
            		}
            		else {
            			Ext.Msg.alert('Fallo en pedido', 'Comunicaci&oacute; AJAX fallida!!!');
            		}
            	}, scope: this
            });
    	}
    	else { // data created in the client (autosave == false)
    		//console.log('created from client');
    		var defaultData = {
    	    	title: rec.data.title,
    			authors: rec.data.authors,
    			documentType: rec.data.documentType,
    			year: rec.data.year,
    			pages: rec.data.pages,
    			publishedin: rec.data.publishedin,
    			abstract: rec.data.abstract,
    			keywords: rec.data.keywords,
    			files: rec.data.files
    		};
    		// this is used with documentDetailsStore
    		// create a new record from 
    		this.record = new this.documentDetailsStore.recordType(defaultData, rec.id); // create new record
    		this.documentDetailsStore.add(this.record); // insert a new record into the store
    		this.buildFormByDocumentType(documentType);
	        this.getForm().loadRecord(this.record);
    	}
    	
    },

    /**
     * onUpdate
     */
    onUpdate : function(btn, ev) {
        if (this.record == null) {
            return;
        }

        if (!this.getForm().isValid()) {
            App.setAlert(false, "Formulario inv&aacute;lido.");
            return false;
        }
        
        var values = this.getForm().getValues();
        
        this.getForm().updateRecord(this.record); // update the data store attached to the form
        if( !this.documentDetailsStore.autoSave ) {
        	this.documentDetailsStore.save();  
        }
    },

    /**
     * onCreate
     */
    onCreate : function(btn, ev) {
        if (!this.getForm().isValid()) {
            App.setAlert(false, "Formulario inv&aacute;lido");
            return false;
        }
        
        // get data and add it to the store
        var data = this.getForm().getValues();
        var rec = new this.documentDetailsStore.recordType(data);
        this.documentDetailsStore.add(rec);
        
        // we should call to the save() function into the store to force the create
        // because this operation is obligated in the form behavior 
        if( !this.documentDetailsStore.autoSave ) {
        	this.documentDetailsStore.save();  
        }
        
        //this.fireEvent('create', this, this.getForm().getValues());
        //this.getForm().reset();
    },

    /**
     * onReset
     */
    onReset : function(btn, ev) {
        this.fireEvent('update', this, this.getForm().getValues());
        this.getForm().reset();
        this.linkedGrid.record.reject();
    	//var r = this.linkedGrid.store.getById(this.record.id);
    	//if( r != undefined ) {
    		//r.reject();
    	//}
    },
    
    setLinkedGrid: function(grid) {
    	this.linkedGrid = grid;
    },
    
    onActionComplete: function() {
    },
    
    /**
     * event executed for each field on the form.
     * evento executado para cada campo en el formulario.
     */
    onChange: function( field, newValue, oldValue ) {
    	if (this.ownerCt.record == null) {
            return;
        }

        if (!this.ownerCt.getForm().isValid()) {
            this.ownerCt.application.setAlert(false, "Formulario inv&aacute;lido.");
            return false;
        }
        
        if( this.ownerCt.documentDetailsStore.autoSave ) {
        	this.ownerCt.getForm().updateRecord(this.ownerCt.record);
        	if( this.ownerCt.linkedGrid.record.data[field.name] != undefined ) {
        		// este tipo de asignacion forzada elimina todo el mecanismo de activacion de 
        		// campos dirty y en esta caso es muy util pues no queremos ejecutar un update 
        		this.ownerCt.linkedGrid.record.data[field.name] = newValue;
        		this.ownerCt.linkedGrid.getView().refreshRow(this.ownerCt.linkedGrid.record);
        	}
        	// if we are in autoSave mode, we should load the record to become the default values
        	this.ownerCt.getForm().loadRecord(this.ownerCt.record);
        }
        else {
        	this.ownerCt.getForm().updateRecord(this.ownerCt.record);
        	//var r = this.ownerCt.linkedGrid.store.getById(this.ownerCt.record.id);
        	//if( r.data[field.name] != undefined ) {
        	//	r.set(field.name, newValue);
        	//	this.ownerCt.linkedGrid.store.add(r);
        	//}
        	if( this.ownerCt.linkedGrid.record.data[field.name] != undefined ) {
        		this.ownerCt.linkedGrid.record.set(field.name, newValue);
        		//this.ownerCt.linkedGrid.store.add(this.ownerCt.linkedGrid.record);
        	}
        }
    },
    
    /**
     * 
     */
    onDocumentTypeComboboxChange: function( field, newValue, oldValue ) {
    	if (this.ownerCt.record == null) {
            return;
        }

        if (!this.ownerCt.getForm().isValid()) {
        	this.ownerCt.application.setAlert(false, "Formulario invalido.");
            return false;
        }
        
        // save the writer writeAllFields state
        this.ownerCt.documentDetailsStore.writerWriteAllFieldsState = this.ownerCt.documentDetailsStore.writer.writeAllFields;
		// we must send all field to the server
        this.ownerCt.documentDetailsStore.writer.writeAllFields = true;
        
        //if ( this.ownerCt.documentDetailsStore.autoSave ) {
    	Ext.MessageBox.show({ 
        	title: 'Cambio de Tipo de Documento', 
        	buttons: Ext.MessageBox.YESNO,
        	msg: 'Tenga cuidado al cambiar el "Tipo de Documento"!!!. Puede que el nuevo tipo que usted ha seleccionado ' +
        		'no contenga los mismo campos para almacenar la informaci&oacute;n actual y esta se pueda perder. Desea proseguir con el cambio?', 
        	icon: Ext.MessageBox.WARNING,
        	
        	fn: function(btn){
    			if (btn == 'yes') { 
    				// TODO: include the change of form and the assign of new values
    				this.ownerCt.getForm().updateRecord(this.ownerCt.record);
    				if ( !this.ownerCt.documentDetailsStore.autoSave ) {
    					this.ownerCt.documentDetailsStore.save();
    				}
    				// the record mush be reload in order to display the new form
    				this.ownerCt.refreshRecord = true;
    			}
    			else {
    				field.setValue(oldValue);
    			}
    		},
    		scope: this
    	});
       // }
        /*
        else {
        	var gridStore = this.ownerCt.linkedGrid.store;
        	var documentForm = this.ownerCt;
        	
        	documentForm.getForm().updateRecord(documentForm.record);
        	
            var r = gridStore.getById(documentForm.record.id);
            r.data.documentType = newValue;
            gridStore.add(r);
            //documentForm.loadRecord(r);
        }
        */
    },
    
    /**
     * result: record.data
     * res: result = action text + record.data + message + success flag
     */
    onStoreWrite: function( store, action, result, res, rs ) {
    	if( action == 'update' ) {
    		// back the writeAllFields state attribute to the normality 
    		this.writer.writeAllFields = this.writerWriteAllFieldsState;
    		
    		// commit after the record changes after the success update
    		store.ownerCt.linkedGrid.record.commit();
    		if(store.ownerCt.refreshRecord) {
    			store.ownerCt.loadRecord(rs);
    			store.ownerCt.refreshRecord = false;
    			//reload the grid
    			store.ownerCt.linkedGrid.store.reload();
    		}
    	}
    	else if( action == 'create' ) {
    		store.ownerCt.linkedGrid.store.reload();
    	}
    },
    
    onStoreLoad: function( /*Store*/ store, /*Ext.data.Record[]*/ records, /*Object*/ options ) {
    	// usando este evento estamos asignando el primer elemento del arrego files a files hasta que la aplicacion soporte 
    	// multiples archivos en el formulario de edicion.
    	
    	//console.log(options);
//    	options.scope.files = records[0].data.files;
//    	records[0].data.files = options.scope.files[0].name;
    },
    
    convertCatalogs: function(v, record) {
    	return (v.length > 0) ? v[0].identification : '';
    },
    
    convertFiles: function(v, record) {
    	return (v.length > 0) ? v[0].name : '';
    },
    
    convertURLs: function(v, record) {
    	return (v.length > 0) ? v[0].url : '';
    }
});